package com.hkh.erp.system.api;


import cn.hutool.core.lang.UUID;
import com.hkh.erp.common.api.RespException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器，添加
 * @author huangkh
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    private final static String REQUEST_ID = "REQUEST_ID";
    private final static String TIMESTAMP_ID = "TIMESTAMP_ID";
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws RespException {
        String requestId = UUID.fastUUID().toString().split("-")[4];
        MDC.put(REQUEST_ID,requestId);
        MDC.put(TIMESTAMP_ID,Long.toString(System.currentTimeMillis()));
        log.info("================      requestId: " + requestId + " 开始             =================");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("================      requestId: " + MDC.get(REQUEST_ID) + " 结束 消耗ms:"+ (System.currentTimeMillis()- Long.parseLong(MDC.get(TIMESTAMP_ID)))+"   =================");
        MDC.remove("REQUEST_ID");
        MDC.remove("TIMESTAMP_ID");
    }
}

